
module Readline_hack where

import System.Console.Readline
import Maybe

import SParser
import RPTypes

import Control.Monad.Error

import System.Process
import System.IO

readQuery :: String -> String -> IO (Maybe String)
readQuery prompt thusread = 
       do putStrLn "Starting ..."
          inth <- readline prompt
          putStrLn "Read data ..."
          if (isJust inth)
            then do if (hasPeriod $ fromJust inth)
                       then return (Just (thusread ++ (cr thusread) ++ (fromJust inth)))
                       else readQuery "  > " (thusread ++ (cr thusread) ++ (fromJust inth))  
            else do putStrLn "We read nothing --- exiting !"
                    return Nothing
       where
          hasPeriod l = elem '.' l
          cr [] = ""
          cr _ = " "


-- A bit nasty, relies on old rp2 code
parseQuery1 :: String -> IO (ParseMonad Term,ParseMonad Term)
parseQuery1 q = do putStrLn ("About to run: " ++ (yapc q))
                   (_,handle,_,_) <- runInteractiveCommand (yapc q)
                   line1 <- hGetLine handle
                   putStrLn ("Got " ++ line1)
                   line2 <- hGetLine handle
                   putStrLn ("Result is:\n" ++ line1 ++ "\n" ++ line2 ++"\n")
                   return (parseString line1 1,parseString line2 2)
                where parseString x n = parseTerm $ markString ("Interactive interpreter " ++ show n) x

yapc q = "yap -l rp2_hu.pl -- '" ++ q ++ "'"

parseQuery2 :: ParseMonad Term -> ParseMonad Term -> ParseMonad (Term, Term)
parseQuery2 q1 q2 = 
             either (Left)
                    (\x -> (either (Left) 
                            (\y -> Right (x,y)) 
                            q2))
                    q1

parseQuery :: String -> IO (ParseMonad (Term,Term))
parseQuery str =
    do (q1,q2) <- parseQuery1 str
       return (parseQuery2 q1 q2)

{-
main :: IO ()
main = do str <- readQuery " ?- " []
          if isJust str
             then do putStrLn $ "GOT: " ++ (fromJust  str)
                     addHistory (fromJust str)
                     query <- parseQuery $ fromJust str 
                     either (\x -> do putStrLn ("Query Error " ++ show x)
                                      return ())
                            (\(x,y) -> do putStrLn ("Got Query D: " ++ (show x) ++ " I: " ++ (show y))
                                          main)
                            query
             else putStrLn "Exiting"

-}